<script setup>
import { ref } from 'vue';

defineOptions({
  name: 'Role',
});
import {
  getRolePage,
  getAllRoles,
  saveRole,
  deleteRole,
  getRoleDetail,
} from '@/api/role';
import { assignRolePermissions } from '@/api/permission';
import { getAllMenus } from '@/api/menu';
import { baseColumns } from './columns';
import { buildTree } from '@/utils/buildTree';
import editRoleDialog from './com/editRoleDialog.vue';
import { useFormModal,useConfirm,message } from '@/hooks/modal';
import {debounce} from 'lodash';

import YLoopMenu from './com/YLoopMenu.vue';

const { openModal } = useFormModal();
const {warning} = useConfirm();

const initForm = {
  name: '',
  code: '',
  status: 1,
  description: '',
};
const searchRoleName = ref('');
const formState = ref({});
const menuTree = ref([]);
const configTableRef = ref(null);
const requestParams = reactive({
  name: searchRoleName.value,
})


const refreshTable = ()=>{
  configTableRef.value.refresh();
}


// 获取角色详情
async function _info(roleId) {
  if (roleId) {
    const roleRes = await getRoleDetail(roleId);
    if (roleRes) {
      roleRes.permissions = roleRes.permissions.map((item) => {
        return {
          menuId: item.menuId,
          actions: item.actions,
        };
      });
    }
    formState.value = roleRes;
  }
}

// 初始化
const init = async () => {
  try {
    const menuRes = await getAllMenus();
    menuTree.value = buildTree(menuRes);
  } finally {
  }
};
init();

const open = (role) => {
  openModal(editRoleDialog, role).then(async (roleRes)=>{
    if(roleRes){
      await saveRole(roleRes);
      message.success('保存成功');
      refreshTable();
    }
  })
}


// 分配权限
const assignPermission = async (role) => {
  const { id, permissions } = role;
  if(!id){
    message.warning('请选择角色');
    return;
  }
  const data = {
    roleId: id,
    permissions: permissions,
  };
  try {
    await assignRolePermissions(data);
    await _info(formState.value.id);
  } catch {}
};

const filterRoleList = debounce((roleName) => {
  requestParams.name = roleName;
}, 500);
const handleAddRole = () => {
  open(initForm);
};
const handleEdit = ({ record }) => {
  open(record);
};

const handleDelete = ({record}) => {
  warning(`确认删除角色${record.name}吗？删除后不可恢复！`).then(async ()=>{
    await deleteRole(record.id);
    message.success('删除成功');
    refreshTable();
  })
};
const handleInfo = ({ record }) => {
  _info(record.id);
};

const columns = [
  ...baseColumns,
  {
    title: '操作',
    dataIndex: 'action',
    minWidth: 150,
    actions: [
      {
        label: '详情',
        type: 'link',
        size: 'small',
        danger: true,
        onClick: handleInfo,
      },
      {
        label: '编辑',
        type: 'link',
        size: 'small',
        danger: true,
        onClick: handleEdit,
      },
      {
        label: '删除',
        type: 'link',
        size: 'small',
        danger: true,
        onClick: handleDelete,
      },
    ],
  },
];
</script>

<template>
  <y-layout-split>
    <template #left>
      <div class="flex h-full flex-col">
        <div class="mb-4 flex">
          <div class="flex-1 mr-3">
            <a-input
              v-model:value="searchRoleName"
              placeholder="请输入角色名称"
              @change="filterRoleList(searchRoleName)"
            ></a-input>
          </div>
          <div>
            <a-button type="primary" @click="handleAddRole">新增</a-button>
          </div>
        </div>
        <div class="flex-1">
          <y-config-table
          ref="configTableRef"
            :dataRequest="getAllRoles"
            :requestParams="requestParams"
            :columns="columns"
          ></y-config-table>
        </div>
      </div>
    </template>
    <template #right>
      <div class="mb-8">
        <h2 class="text-2xl font-bold mb-4">{{ formState.name }}- 权限配置</h2>
        <p>{{ formState.description }}</p>
      </div>

      <div style="height: calc(100% - 70px)" class="p-6">
        <h3 class="text-lg font-semibold mb-4 flex items-center">
          <i class="fa-solid fa-bars mr-2"></i>
          <span> 菜单权限 </span>
        </h3>
        <div
          style="max-height: calc(100% - 38.5px - 70px)"
          class="overflow-y-auto mb-4"
        >
          <YLoopMenu
            :menus="menuTree"
            :permissions="formState.permissions"
            class="mb-4"
          ></YLoopMenu>
        </div>
        <div>
          <a-space>
            <a-button type="primary" @click="assignPermission(formState)"
              >保存</a-button
            >
            <a-button type="primary">重置</a-button>
          </a-space>
        </div>
      </div>
    </template>
  </y-layout-split>
</template>
